# -*- coding: cp1254 -*-
import datetime
from django.contrib import *
from gma.game.models import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from random import randint
from django.core import serializers


def login(request):
    usr = request.POST["user"]
    pas = request.POST["pass"]
    user = auth.authenticate(username=usr, password=pas)
    if user is not None:
        if user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect("/index/")
        else:
            return HttpResponseRedirect("/index/login/")
    else:
        return HttpResponseRedirect("/index/register/")
    
def alogin(request):
    return render_to_response("login.html")

def register(request):
    usr = request.POST["user"]
    pas = request.POST["pass"]
    aUser = User.objects.create_user(usr,"",pas)
    aUser.is_active=True
    aUser.save()
    return render_to_response("login.html")

def aregister(request):
    return render_to_response("register.html")

@login_required (redirect_field_name='')
def logout(request):
    if request.user.is_authenticated:
       auth.logout(request)
    return HttpResponseRedirect("/thought/none/index-left.html")

@login_required (redirect_field_name='')
def create_char(request):
    return render_to_response("create.html")

@login_required (redirect_field_name='')
def save_char(request):
    name = request.POST["name"]
    race = request.POST["race"]
    sex = request.POST["gender"]
    
    char = Character.init(request,name,race,sex)
    
    return render_to_response("index.html",{"current":char.current_place})

@login_required (redirect_field_name='')
def char_panel(request):
    char = Character.objects.get(user=request.user)
    try:
        return render_to_response("char.html",char.return_all())
    except Character.DoesNotExist:
        return render_to_response("create.html")

def edit_cell(request):
    return render_to_response("celleditor.html",{"cells":Place.objects.all()})

def save_cell(request):
    name=request.POST["name"]
    category=request.POST["group"]
    p=Place.objects.create(name=name,category=category)
    try:
        links_n=request.POST["linksn"]
        links_s=request.POST["linkss"]
        links_w=request.POST["linksw"]
        links_e=request.POST["linkse"]
        p.connection.add(Place.objects.get(name=links_n))
        p.connection.add(Place.objects.get(name=links_s))
        p.connection.add(Place.objects.get(name=links_w))
        p.connection.add(Place.objects.get(name=links_e))
    except:
        pass
    p.save()
    return render_to_response("index.html")
    
@login_required (redirect_field_name='')
def edit_item(request):
    return render_to_response("itemeditor.html",{'cells':Place.objects.all()})
    
@login_required (redirect_field_name='')
def  save_item(request):
    name=request.POST["name"]
    category=request.POST["category"]
    value=request.POST["value"]
    cell=request.POST["cells"]
    cat,typec = category.split(' ')
    i=Item.objects.create(name=name,type='item',category=cat,typeclass=typec,value=value,x=randint(100,550),y=randint(330,390),marked=False)
    i.save()
    p=Place.objects.get(name=cell)
    p.people.add(i)
    p.save()
    return render_to_response("index.html")
    
@login_required (redirect_field_name='')
def main_page(request):
    c=Character.objects.get(user=request.user)
    return render_to_response("index.html",{"current":c.current_place})

@login_required (redirect_field_name='')
def render(request,cell):
    try: c=Character.objects.get(user=request.user)
    except: return render_to_response("create.html")   
    p1=Place.objects.get(name=c.current_place)
    try:
        p2=Place.objects.get(name=cell)
    except:
        li=p1.people.order_by("y")
        return render_to_response("render.html",{"current":p1,"people":li,"my":c.name})
    
    if p2 in p1.connection.all():
        c.travel(cell)
        c.state=0
    
    if not p2.name==p1.name:
        try:
            c1=InterreactionBox.objects.get(first=c);
            c1.decompose()
        except InterreactionBox.DoesNotExist: pass
    
        try:
            c2=InterreactionBox.objects.get(second=c);
            c2.decompose()
        except InterreactionBox.DoesNotExist: pass
        

    li=p2.people.order_by("y")
    
    p1.save()
    p2.save()
    c.save()

    return render_to_response("render.html",{"current":p2,"people":li,"my":c.name})
    
@login_required (redirect_field_name='')
def index_re(request):
    try: c=Character.objects.get(user=request.user)
    except: return render_to_response("create.html")
    p2=Place.objects.get(name=c.current_place)
    li=p2.people.order_by("y")
    c.save()

    return render_to_response("render.html",{"current":p2,"people":li,"my":c.name})
    
def getlist(request):
    char=Character.objects.get(user=request.user)
    cell=Place.objects.get(name=char.current_place)
    people=cell.people.order_by("y")
    data=''
    data = data + '<img src="/index/files/blank.gif" onload="pageLoad();return false;"></img>'
    for e in people:
        if e.type=='char':
            modifier = 0 if e.character.race=="Dark Elf" else 42 if e.character.race=="Orc" else 40 if e.character.race=="High Elf" else 10 if e.character.race=="Human" else -100
        else: modifier = 0
        
        if e.name == char.name:
            data = data + '<div style="position: absolute; left:'+str(e.character.x-2*len(e.name)+18)+'px; top:'+str(e.y-(20+1.5*modifier))+'px; width: 571px; height: 16px; text-align: justify;" align="right"><font color="#ffffff" size="2" style="background-color:#24507b" face="Verdana">'+str(e.name)+'</font></div><div id="ldheRect1" style="position: absolute; left:'+str(e.character.x)+'px; top:'+str(e.y-(1.4*modifier))+'px;" align="left" ><a href="/index/char/" class="cBox"><img src="/index/files/char_'+str(e.character.race)+'_'+str(e.character.gender)+'.gif" height="'+str(e.y-260+modifier)+'" border="0" alt="me"></a></div>'
            
        elif e.name == 'iBox':
            if(e.interreactionbox.first.name == char.name or e.interreactionbox.second.name == char.name):
                data = data + '<div style="position: absolute;left:'+str(e.interreactionbox.x-2*len(e.name)-11)+'px; top:'+str(e.y-20)+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff"size="2"face="Verdana" style="background-color:#24507b">'+str(e.interreactionbox.first.name)+' and '+str(e.interreactionbox.second.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.interreactionbox.x)+'px;top:'+str(e.y)+'px;"align="left"><a href="/index/interreact/'+str(e.interreactionbox.first.name)+'/'+str(e.interreactionbox.second.name)+'/" class="iBox"><img src="/index/files/interreact.gif "height="'+str(e.y-260)+'" border="0" alt="'+str(e.interreactionbox.name)+'"></a></div>'  
            else:
                data = data + '<div style="position: absolute;left:'+str(e.interreactionbox.x-2*len(e.name)-11)+'px; top:'+str(e.y-20)+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff"size="2"face="Verdana" style="background-color:#24507b">'+str(e.interreactionbox.first.name)+' and '+str(e.interreactionbox.second.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.interreactionbox.x)+'px;top:'+str(e.y)+'px;"align="left"> <img src="/index/files/interreact.gif "height="'+str(e.y-260)+'" border="0" alt="'+str(e.interreactionbox.name)+'"></div>'  
            
            
        elif e.type == 'item':
            if e.item.typeclass=='document':
                data = data + '<div style="position: absolute;left:'+str(e.item.x-(2*len(e.name)-10))+'px; top:'+str(e.y+5)+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff"size="2" style="background-color:#24507b" face="Verdana">'+str(e.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.item.x)+'px;top:'+str(e.y+36)+'px;"align="left"><a href="/index/docs/'+str(e.item.category)+'.html/" class="dBox"><img src="/index/files/item.gif "height="'+str(e.y-305)+'" border="0" alt="'+str(e.item.name)+'"></a></div>'
            else:
                data = data + '<div style="position: absolute;left:'+str(e.item.x-(2*len(e.name)-10))+'px; top:'+str(e.y+5)+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff"size="2" style="background-color:#24507b" face="Verdana">'+str(e.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.item.x)+'px;top:'+str(e.y+36)+'px;"align="left"><img src="/index/files/item.gif "height="'+str(e.y-305)+'" border="0" alt="'+str(e.item.name)+'" onclick="takeItem('+ str(e.id) +');"></div>'
        else:
            if char.state:
                data = data + '<div style="position: absolute;left:'+str(e.character.x-3*len(e.name)+18)+'px; top:'+str(e.y-(20+1.5*modifier))+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff" style="background-color:#24507b" size="2"face="Verdana">'+str(e.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.character.x)+'px;top:'+str(e.y-(1.4*modifier))+'px;"align="left"><img src="/index/files/char_'+str(e.character.race)+'_'+str(e.character.gender)+'.gif" height="'+str(e.y-260+modifier)+'" border="0"></div>'                                                                                                                                                                                                                          
            else:
                data = data + '<div style="position: absolute;left:'+str(e.character.x-3*len(e.name)+18)+'px; top:'+str(e.y-(20+1.5*modifier))+'px;width:571px; height: 16px; text-align: justify;"align="right"><font color="#ffffff" style="background-color:#24507b" size="2"face="Verdana">'+str(e.name)+'</font></div><div id="ldheRect1"style="position:absolute;left:'+str(e.character.x)+'px;top:'+str(e.y-(1.4*modifier))+'px;"align="left"><a class="iBox" href="/index/interreact/'+str(char.character.name)+'/'+str(e.character.name)+'/"><img src="/index/files/char_'+str(e.character.race)+'_'+str(e.character.gender)+'.gif" height="'+str(e.y-260+modifier)+'" border="0"></a></div>'                                                                                                                                                                                                                          
    
    return HttpResponse(data)

@login_required (redirect_field_name='')
def interreact(request,first,other):
    myself = Character.objects.get(user=request.user)
    firstone = Character.objects.get(name=first)
    print first
    otherone  = Character.objects.get(name=other)
    otherself = firstone if myself.name == otherone.name else otherone
    place = Place.objects.get(name=firstone.current_place)
    
	
    if(firstone.state == 0 and otherone.state == 0):
        firstone.state=1
        otherone.state=1
        if(firstone.current_place==otherone.current_place):
            iBox = InterreactionBox(name='iBox',type='iBox',first=firstone,second=otherone,current_place=firstone.current_place,x=otherone.x*0.77,y=otherone.y*0.98)
            otherone.contacts.add(firstone)
            place.people.remove(firstone)
            firstone.contacts.add(otherone)
            place.people.remove(otherone)
            iBox.save()
            place.people.add(iBox)
            firstone.save()
            otherone.save()
            place.save()
    else:
            iBox = InterreactionBox.objects.get(first=firstone)
            other = iBox.second.name
            
    placing = 1 if iBox.first.name == myself.name else 2
    return render_to_response('interreact.html',{"p":placing,"s1":myself.state-1,"s2":otherself.state-1,"inventory":myself.inventory.all(),"box1":iBox.item_box1.all(),"box2":iBox.item_box2.all()})

@login_required (redirect_field_name='')
def interrupt(request,me):
    myself = Character.objects.get(name=me)
    place = Place.objects.get(name=myself.current_place)
    try:
        iBox= InterreactionBox.objects.get(first=myself)
        place.people.remove(iBox)
    except InterreactionBox.DoesNotExist:
        iBox= InterreactionBox.objects.get(second=myself)
        place.people.remove(iBox)
    iBox.decompose()
    place.save()
    
    return None

@login_required (redirect_field_name='')    
def box1(request):
    myself = Character.objects.get(user=request.user)
    try: iBox = InterreactionBox.objects.get(first=myself)
    except: iBox =InterreactionBox.objects.get(second=myself)
    items= iBox.item_box1.all()
    data=''
    for item in items:
        data += '<option value="'+str(item.id)+'">'+str(item.name)+'</option>'
    return HttpResponse(data)

@login_required (redirect_field_name='')
def box2(request):
    myself = Character.objects.get(user=request.user)
    try: iBox = InterreactionBox.objects.get(first=myself)
    except: iBox =InterreactionBox.objects.get(second=myself)
    items= iBox.item_box2.all()
    data=''
    for item in items:
        data += '<option value="'+str(item.id)+'">'+str(item.name)+'</option>'
    return HttpResponse(data)
    

@login_required (redirect_field_name='')
def exchange_signal(request):
    myself = Character.objects.get(user=request.user)
    try: 
        iBox = InterreactionBox.objects.get(first=myself)
        other = iBox.second
    except: 
        iBox =InterreactionBox.objects.get(second=myself)
        other = iBox.first  
    if myself.state-1 and other.state-1:
        status = '''<div id="wb_Text2" style="margin:0;padding:0;position:absolute;left:0px;top:0px;width:110px;height:14px;text-align:left;z-index:7;">
<font style="font-size:11px"  color="#00fa00" face="Arial"> You are ready! </font></div>
<div id="wb_Text1" style="margin:0;padding:0;position:absolute;left:2px;top:20px;width:90px;height:28px;text-align:left;z-index:8;">
<font style="font-size:11px" color="#00ff00" face="Arial">Peer is ready!</font></div>'''

    elif myself.state-1 and not other.state-1:
        status = '''<div id="wb_Text2" style="margin:0;padding:0;position:absolute;left:0px;top:0px;width:110px;height:14px;text-align:left;z-index:7;">
<font style="font-size:11px"  color="#00fa00" face="Arial"> You are ready! </font></div>
<div id="wb_Text1" style="margin:0;padding:0;position:absolute;left:2px;top:20px;width:90px;height:28px;text-align:left;z-index:8;">
<font style="font-size:11px" color="#000000" face="Arial">Waiting for peer</font></div>'''

    elif not myself.state-1 and other.state-1:
        status = '''<div id="wb_Text2" style="margin:0;padding:0;position:absolute;left:0px;top:0px;width:110px;height:14px;text-align:left;z-index:7;">
<font style="font-size:11px"  color="#fa0000" face="Arial">You are not ready!</font></div>
<div id="wb_Text1" style="margin:0;padding:0;position:absolute;left:2px;top:20px;width:90px;height:28px;text-align:left;z-index:8;">
<font style="font-size:11px" color="#00fa00" face="Arial">Peer is ready!</font></div>'''

    elif (not myself.state-1) and not other.state-1:
        status = '''<div id="wb_Text2" style="margin:0;padding:0;position:absolute;left:0px;top:0px;width:110px;height:14px;text-align:left;z-index:7;">
<font style="font-size:11px"  color="#fa0000" face="Arial">You are not ready!</font></div>
<div id="wb_Text1" style="margin:0;padding:0;position:absolute;left:2px;top:20px;width:90px;height:28px;text-align:left;z-index:8;">
<font style="font-size:11px" color="#fa0000" face="Arial">Peer is not ready!</font></div>'''
    else: status = '''<div id="wb_Text2" style="margin:0;padding:0;position:absolute;left:0px;top:0px;width:110px;height:14px;text-align:left;z-index:7;">
<font style="font-size:11px"  color="#fa0000" face="Arial">An Exception Occured</font></div>'''
    return HttpResponse(status)
    

 
@login_required (redirect_field_name='') 
def show_inventory_async(request):
    myself = Character.objects.get(user=request.user)
    inventory = myself.inventory.all()
    data=''
    for item in inventory:
        data += '<option value="'+str(item.id)+'">'+str(item.name)+'</option>'
    return HttpResponse(data)

@login_required (redirect_field_name='')
def interreact_action(request):
    myself = Character.objects.get(user=request.user)
    try: 
        iBox = InterreactionBox.objects.get(first=myself)
        other = iBox.second
    except: 
        iBox =InterreactionBox.objects.get(second=myself)
        other = iBox.first
    
    placing = 1 if iBox.first.name == myself.name else 2
    item_box = iBox.item_box1 if placing is 1 else iBox.item_box2
    
    option = request.POST["benjamin"]
    option = option.strip()
    try: 
        item_id = request.POST["inventory"]
        item = Item.objects.get(id=item_id)
        if option == 'Give':
            myself.inventory.remove(item)
            item_box.add(item)
            s1 = False
    except: 
        try: 
            item_id = request.POST["mybox"]
            item = Item.objects.get(id=item_id)
            if option == 'Take':
                item_box.remove(item)
                myself.inventory.add(item)
                s1 = False
        except:
            if option == 'Ready':
                myself.state = 2
                myself.save()
            elif option == 'Break':
                myself.state = 1
                myself.save()
            elif option == 'Confirm':
                if myself.state-1 and other.state-1:
                    for item in iBox.item_box2.all():
                        iBox.item_box2.remove(item)
                        myself.inventory.add(item)
                        
                    for item in iBox.item_box1.all():
                        iBox.item_box1.remove(item)
                        other.inventory.add(item)
                        
                    myself.state = 1 
                    myself.save()
                    other.state = 1
                    other.save()
                    placing = 1 if iBox.first.name == myself.name else 2        
    return render_to_response('interreact.html',{"p":placing,"s1":myself.state-1,"s2":other.state-1,"inventory":myself.inventory.all(),"box1":iBox.item_box1.all(),"box2":iBox.item_box2.all()})
            
@login_required (redirect_field_name='')
def show_inventory(request):
    myself = Character.objects.get(user=request.user)
    inventory = myself.inventory.all()
    return render_to_response("inventory.html",{"inventory":inventory})
	
@login_required (redirect_field_name='')
def item_action(request):
    try:
        item_id = request.POST["inventory"]
    except: render_to_response("inventory.html",{"inventory":inventory})
    item = Item.objects.get(id=item_id)
    char = Character.objects.get(user=request.user)
    inventory = char.inventory.all()
    print "\n cemil \n"
    pressed = request.POST["Btn"]
    print "\n sen \n"
    if pressed == "Use/Equip":
        print "\n bir \n"
        item.use(char)
        
    elif pressed == "Toss":
        cell = Place.objects.get(name=char.current_place)
        char.inventory.remove(item)
        item.x=char.x+randint(-5,5)
        item.y=char.y+5
        cell.people.add(item)
        cell.save
        
    elif pressed == "Mark/Unmark":
        item.marked = ~item.marked
    
    item.save()
    char.save()
    return render_to_response("inventory.html",{"inventory":inventory})

@login_required (redirect_field_name='')
def take_item(request,id,proc):
    char = Character.objects.get(user=request.user)
    cell = Place.objects.get(name=char.current_place)
    item = Item.objects.get(id=id)
    if proc == "ground":
        cell.people.remove(item)
        char.inventory.add(item)
        return HttpResponseRedirect('/index/render/'+cell.name)
    else:
        char.inventory.add(item)
        if char.pants.id == int(id): char.pants=None
        elif char.shirt.id == int(id): char.shirt=None
        elif char.gloves.id == int(id): char.gloves=None
        elif char.hat.id == int(id): char.hat=None
        char.save()
    	return HttpResponseRedirect('/index/render/'+cell.name)

@login_required (redirect_field_name='')
def send_msg(request):
    myself = Character.objects.get(user=request.user)
    try:
        iBox= InterreactionBox.objects.get(first=myself)
    except InterreactionBox.DoesNotExist:
        iBox= InterreactionBox.objects.get(second=myself)
        
    message = request.POST["msg_content"]
    iBox.message_box = iBox.message_box + '\n' + str(myself.name) + ": " + message
    if iBox.message_box.count('\n')>9:
        iBox.message_box= "".join(iBox.message_box.splitlines(True)[1:])
    iBox.save()
    placing = 1 if iBox.first.name == myself.name else 2
    return render_to_response('interreact.html',{"p":placing,"s1":myself.state-1,"inventory":myself.inventory.all(),"box1":iBox.item_box1.all(),"box2":iBox.item_box2.all()})
    
def get_msg_list(request):
    myself = Character.objects.get(user=request.user)
    try:
        iBox= InterreactionBox.objects.get(first=myself)
    except InterreactionBox.DoesNotExist:
        iBox= InterreactionBox.objects.get(second=myself)
    return HttpResponse(iBox)